# -*- coding: utf-8 -*-
# @Author : HaleShi
# @Time : 2023-06-06
# @File : 11_did_complete.py

import random
import string
import base64


def base64_encrypt(data_string):
    data_bytes = bytearray(data_string.encode('utf-8'))
    data_bytes[0] = data_bytes[0] ^ (len(data_bytes) & 0xFF)
    for i in range(1, len(data_bytes)):
        data_bytes[i] = (data_bytes[i - 1] ^ data_bytes[i]) & 0xFF
    res = base64.encodebytes(bytes(data_bytes))
    return res.strip().strip(b"==").decode('utf-8')


def create_random_mac(sep=":"):
    """ 随机生成mac地址 """
    data_list = []
    for i in range(1, 7):
        part = "".join(random.sample("0123456789ABCDEF", 2))
        data_list.append(part)
    mac = sep.join(data_list)
    return mac


def gen_sn():
    return "".join(random.sample("123456789" + string.ascii_lowercase, 10))


def get_did():
    mac_string = create_random_mac(sep="")
    sn = gen_sn()

    did = base64_encrypt("{}|||".format(mac_string))
    return did

def get_sign(data_string):
    import hashlib
    salt = "9cafa6466a028bfb"
    obj = hashlib.sha256()
    obj.update(data_string.encode('utf-8'))
    obj.update(salt.encode('utf-8'))
    return obj.hexdigest()


def body_encrypt(data):
    from Crypto.Cipher import AES
    from Crypto.Util.Padding import pad

    KEY = "fd6b639dbcff0c2a1b03b389ec763c4b"
    IV = "77b07a672d57d64c"

    def aes_encrypt(data_string):
        aes = AES.new(
            key=KEY.encode('utf-8'),
            mode=AES.MODE_CBC,
            iv=IV.encode('utf-8')
        )
        raw = pad(data_string.encode('utf-8'), 16)
        return aes.encrypt(raw)

    # 字节类型
    bytes_data = aes_encrypt(data)
    return bytes_data

def run():
    did = get_did()

    data_dict = {
        "aid": "431518958",
        "auto_play": "2",
        "build": "6240300",
        "cid": "862033117",
        "did": did,
        "epid": "",
        "from_spmid": "tm.recommend.0.0",
        "ftime": "1679394916",
        "lv": "0",
        "mid": "0",
        "mobi_app": "android",
        "part": "0",
        "sid": "0",
        "spmid": "tm.recommend.0.0",
        "stime": "1679404453",
        "sub_type": "0",
        "type": "3",
    }

    # 根据键排序
    ordered_string = "&".join(["{}={}".format(key, data_dict[key]) for key in sorted(data_dict.keys())])

    # 得到sign
    sign = get_sign(ordered_string)

    # 拼接
    data_string = f"{ordered_string}&sign={sign}"

    # AES加密
    body = body_encrypt(data_string)
    print(body)


if __name__ == '__main__':
    run()
